"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const socket_io_stream_1 = __importDefault(require("socket.io-stream"));
const config_1 = require("../config/config");
const chat_helper_1 = require("./chat-helper");
const log4js_1 = require("log4js");
const Member_1 = require("../lib/Member");
const ClassroomEntity_1 = require("../httpServer/entity/ClassroomEntity");
const utils_1 = require("../utils/utils");
const ChatRoomEntity_1 = require("../httpServer/entity/ChatRoomEntity");
const logger = (0, log4js_1.getLogger)('recording');
const fileTypeEnum = {
    audio: 'mp3',
    video: 'mp4'
};
async function queryChatRoom(classId) {
    try {
        const classroom = await ClassroomEntity_1.ClassroomEntity.findOne({ where: { classId } });
        return await ChatRoomEntity_1.ChatRoomEntity.findBy({ classroom });
    }
    catch (e) {
        return Promise.reject(e);
    }
}
function default_1(app) {
    const { socket, intercom, redisClient } = app.locals;
    const { userId, username } = socket.handshake.query;
    function pushChatMessage(members, room, message) {
        const chatContext = { data: message, sender: { userId, username }, room };
        redisClient.hSet('chat-message', room.classId, (0, utils_1.stringify)(message));
        members.forEach(member => {
            var _a;
            if (member.userId !== userId) {
                (_a = intercom[member.userId]) === null || _a === void 0 ? void 0 : _a.emit('chat:message', chatContext);
            }
        });
    }
    socket.on('chat:text', async ({ text, room }, cb = utils_1.noop) => {
        const owner = Member_1.Members.get(userId);
        const message = {
            userId,
            username,
            roomId: room.classId,
            roomName: room.classname,
            content: text,
            contentType: '0',
            messageTime: Date.now(),
        };
        try {
            const body = await owner.axios.chatMessageRecord(message);
            const classroomMembers = await queryChatRoom(room.classId);
            logger.debug('发送聊天消息： =》 ', body);
            if (+body.code === 0) {
                pushChatMessage(classroomMembers, room, message);
                cb({ status: 'ok', data: message });
            }
            else {
                cb({ status: 'error', body });
            }
        }
        catch (error) {
            cb({ status: 'error', error });
        }
    });
    (0, socket_io_stream_1.default)(socket).on('chat:stream', (stream, { fileConfig, receiver, room }, cb = utils_1.noop) => {
        const owner = Member_1.Members.get(userId);
        const { filename, fileType } = fileConfig;
        let resetFilename = (0, chat_helper_1.assembleFilename)(filename, fileType);
        const src = `${config_1.lConfig.chatDirectory}/${resetFilename}`;
        logger.debug('----file:save----', fileConfig, cb);
        stream.pipe(fs_extra_1.default.createWriteStream(src));
        stream.on('error', async (error) => {
            cb && cb({
                status: 'error',
                message: '发送失败！'
            });
        });
        stream.on('end', async () => {
            logger.debug('---- 传输结束，查询房间 ----');
            const message = {
                userId,
                username,
                roomId: room.classId,
                roomName: room.classname,
                content: `/artemis-chat/${resetFilename}`,
                contentType: fileType,
                messageTime: Date.now(),
            };
            const body = await owner.axios.chatMessageRecord(message);
            if (+body.code === 0) {
                const chatContext = { data: message, sender: { userId, username }, room };
                socket.to(room.classId).emit('chat:message', chatContext, () => {
                    cb && cb({
                        status: 'ok',
                        data: message
                    });
                });
            }
            else {
                cb && cb({
                    status: 'error',
                    body
                });
            }
        });
    });
    var arrayBuffer = null;
    socket.on('chat:file', async function (buffer, { fileConfig, receiver, room }, cb = utils_1.noop) {
        const owner = Member_1.Members.get(userId);
        logger.debug('----file:save----');
        const { filename, fileType } = fileConfig;
        const resetFilename = (0, chat_helper_1.assembleFilename)(filename, fileType);
        const src = `${config_1.lConfig.chatDirectory}/${resetFilename}`;
        logger.debug('----file:save----');
        try {
            const classroomMembers = await queryChatRoom(room.classId);
            try {
                await fs_extra_1.default.access(src, fs_extra_1.default.constants.R_OK | fs_extra_1.default.constants.W_OK);
            }
            catch (e) {
                logger.debug('arrayBuffer: => ', arrayBuffer === null || arrayBuffer === void 0 ? void 0 : arrayBuffer.toString());
                if (!arrayBuffer) {
                    arrayBuffer = buffer;
                }
                else {
                    arrayBuffer = Buffer.concat([arrayBuffer, buffer]);
                }
                logger.debug('保存: => ');
                if (fileConfig.total - 1 === fileConfig.current) {
                    fs_extra_1.default.outputFile(src, arrayBuffer, async () => {
                        const message = {
                            userId,
                            username,
                            roomId: room.classId,
                            roomName: room.classname,
                            content: `/artemis-chat/${resetFilename}`,
                            contentType: fileType,
                            messageTime: Date.now(),
                        };
                        arrayBuffer = null;
                        const body = await owner.axios.chatMessageRecord(message);
                        if (+body.code === 0) {
                            pushChatMessage(classroomMembers, room, message);
                            cb({ status: 'ok', data: message });
                        }
                        else {
                            cb({ status: 'error', body });
                        }
                    });
                }
            }
        }
        catch (error) {
            cb({ status: 'error', error });
        }
    });
}
exports.default = default_1;
